package edu.sandau.app.basic.service.impl;

import edu.sandau.app.basic.domain.Favorite;
import edu.sandau.app.basic.domain.FavoriteExample;
import edu.sandau.app.basic.mapper.FavoriteMapper;
import edu.sandau.app.basic.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class FavoriteServiceImpl implements FavoriteService {
    
    @Autowired
    private FavoriteMapper favoriteMapper;
    
    @Override
    public List<Favorite> getUserFavorites(Long userId) {
        FavoriteExample example = new FavoriteExample();
        example.createCriteria().andUserIdEqualTo(userId);
        example.setOrderByClause("create_time DESC");
        return favoriteMapper.selectByExample(example);
    }
    
    @Override
    @Transactional
    public int addFavorite(Favorite favorite) {
        // 检查是否已经收藏
        if (checkFavorite(favorite.getUserId(), favorite.getDishId())) {
            return -1; // 返回-1表示已存在
        }
        
        favorite.setCreateTime(new Date());
        return favoriteMapper.insertSelective(favorite);
    }
    
    @Override
    @Transactional
    public int deleteFavorite(Long id) {
        return favoriteMapper.deleteByPrimaryKey(id);
    }
    
    @Override
    @Transactional
    public int deleteFavoriteByUserAndDish(Long userId, Long dishId) {
        FavoriteExample example = new FavoriteExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andDishIdEqualTo(dishId);
        return favoriteMapper.deleteByExample(example);
    }
    
    @Override
    public boolean checkFavorite(Long userId, Long dishId) {
        FavoriteExample example = new FavoriteExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andDishIdEqualTo(dishId);
        return favoriteMapper.countByExample(example) > 0;
    }
    
    @Override
    public long getDishFavoriteCount(Long dishId) {
        FavoriteExample example = new FavoriteExample();
        example.createCriteria().andDishIdEqualTo(dishId);
        return favoriteMapper.countByExample(example);
    }
    
    @Override
    public Favorite getFavorite(Long userId, Long dishId) {
        FavoriteExample example = new FavoriteExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andDishIdEqualTo(dishId);
        List<Favorite> favorites = favoriteMapper.selectByExample(example);
        return favorites.isEmpty() ? null : favorites.get(0);
    }
}

